<html>

<head>
    <style>
        body {
            margin: 0;
        }
        img {
            /* 解决3px问题 */
            display: block;
            height: 300px;
            width: auto;
        }
    </style>
</head>

<body>

    <ul></ul>

    <script src="../../../demo/jq/jq.js"></script>
    <script>
        const imgSrcList = [];

        for (let i = 0; i < 500; i++) {
            imgSrcList.push({
                title: 'aa',
                src: '../../../goodluck/imgs/arrow.png',
            });
        }

        const ul = $('ul');

        // 每页4张图片
        // currentPage从1开始数
        // pageSize每页的个数
        // 0 ~ 3
        // 4 ~ 7
        // 8 ~ 11
        // (n - 1) * pageSize ~ n * pageSize - 1
        // 2 >>> 4
        // 3 >>> 8
        function createPage (currentPage, pageSize) {
            const currentIndex = (currentPage - 1) * pageSize;
            for (let i = currentIndex; i < currentIndex + pageSize; i++) {
                const li = $(`
                    <li>
                        <div class="title">${ imgSrcList[i].title }</div>
                        <img src="${ imgSrcList[i].src }">
                    </li>
                `);
                ul.append(li);
            }
        }

        let currentPage = 1;
        createPage(currentPage, 4);

        let ready = true;
        // 滚轮事件和滚动条事件的区别
        // 1. 手动拉滚动条不能触发滚轮事件
        // 2. 移动端没有滚轮事件

        function createNew () {
            const windowHeight = window.innerHeight; // 浏览器窗口的高度
            const docHeight = $(document).height(); // 整个文档的高度
            const scrollTop = $(document).scrollTop(); // 卷去的高度
            
            // 如果到底了，执行任务
            if (windowHeight + scrollTop >= docHeight) {
                if (!ready) {
                    return;
                }
                ready = false;
                setTimeout(() => {
                    ready = true;
                }, 3000);
                currentPage++;
                createPage(currentPage, 4);
            }
        }
        
        // $(window).on('wheel', createNew);
        // $(window).on('scroll', createNew);

        $(window).on({
            wheel: createNew,
            scroll: createNew,
        });


    </script>
</body>

</html>